package com.golang.api.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 抽象的拦截器
 */
@Slf4j
public abstract class AbstractHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

  /**
   * 返回前台错误的信息，
   *
   * @param response   错误码
   * @param respObject 错误信息的提示
   */
  protected void responseErrorData (HttpServletResponse response, Result<?> respObject) {
    responseJson(response, JsonHelper.toJson(respObject));
  }

  /**
   * 返回自定义的的字符串
   *
   * @param response
   * @param json
   */
  protected void responseJson (HttpServletResponse response, String json) {
    try {
      response.setContentType("application/json;charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.print(json);
      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  protected Map<String, Object> getRequestParams (HttpServletRequest request) {
    MultiValueMap<String, String> multiValueMap = RequestUtil.getRequestParams(request);
    return MultiValueMapUtil.convert(multiValueMap);
  }

}